/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LogInGUI.java
 *
 * Created on 27/Out/2009, 0:08:24
 */

package tp_sd_cliente.gui;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultFormatter;
import tp_sd_cliente.model.ClientChat;

/**
 *
 * @author kill9
 */
public class LogInGUI extends javax.swing.JDialog{

    private ClientChat clientChat;


    /** Creates new form LogInGUI */
    public LogInGUI(JFrame parent) {
        super(parent, "Configuração ", true);
        initComponents();
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public void setClientChat(ClientChat clientChat) {
        this.clientChat = clientChat;
    }

    

    public void onLogOut(){
        this.setVisible(true);
    }

    public void onLogIn(){
        this.setVisible(false);
    }



    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        ip = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        port = new javax.swing.JFormattedTextField();
        connect = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        reg = new javax.swing.JCheckBox();
        jLabel5 = new javax.swing.JLabel();
        java.util.regex.Pattern evenLength = java.util.regex.Pattern
        .compile("[a-z0-9A-Z]{3,20}");
        name = new javax.swing.JFormattedTextField(new RegexPatternFormatter(evenLength));
        password = new javax.swing.JFormattedTextField(new RegexPatternFormatter(evenLength));

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setBackground(java.awt.Color.white);

        jLabel1.setText("IP:");

        try {
            ip.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###.###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        ip.setText("127.000.000.001");

        jLabel2.setText("Porta:");

        port.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#####0"))));
        port.setText("12345");

        connect.setText("Ligar");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        jLabel3.setText("Nome");

        jLabel4.setText("Palavra Chave");

        jLabel5.setText("Registar");

        name.setText("test");

        password.setText("test");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(reg)
                    .addComponent(connect, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(port, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                    .addComponent(ip, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                    .addComponent(name, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                    .addComponent(password, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(ip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(1, 1, 1))
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(5, 5, 5)
                        .addComponent(connect))
                    .addComponent(reg))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-390)/2, (screenSize.height-265)/2, 390, 265);
    }// </editor-fold>//GEN-END:initComponents

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectActionPerformed
        if(clientChat!=null){
            try {
                byte[] bs = new byte[4];

                int i = 0;
                for (String string : ip.getText().split("\\.")) {
                    bs[i++] = (byte)Integer.parseInt(string);
                    
                }
                int port  = Integer.parseInt(this.port.getText());
                if(port>65535 || port<=0){
                       JOptionPane.showMessageDialog(this, "Number out of bounds", "Erro",JOptionPane.ERROR_MESSAGE);
                       return;
                }
                String login = name.getText().trim();
                String pass = password.getText().trim();
                if(login.length()<3 || login.length()>20 || pass.length()<3 || pass.length()>20){
                    JOptionPane.showMessageDialog(this,"","Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                 clientChat.login(bs, port, name.getText(),password.getText(),reg.isSelected());
            }catch(Exception e){
                JOptionPane.showMessageDialog(this, e.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_connectActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton connect;
    private javax.swing.JFormattedTextField ip;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JFormattedTextField name;
    private javax.swing.JFormattedTextField password;
    private javax.swing.JFormattedTextField port;
    private javax.swing.JCheckBox reg;
    // End of variables declaration//GEN-END:variables


  public class RegexPatternFormatter extends DefaultFormatter {

  protected java.util.regex.Matcher matcher;

  public RegexPatternFormatter(java.util.regex.Pattern regex) {
    setOverwriteMode(false);
    matcher = regex.matcher(""); 
  }

  public Object stringToValue(String string) throws java.text.ParseException {
    if (string == null)
      return null;
    matcher.reset(string); 

    if (!matcher.matches()) 
      throw new java.text.ParseException("does not match regex", 0);

    
    return super.stringToValue(string);
  }
  }

}
